import { Body, Controller, Get, Post, Res, HttpStatus, UploadedFile, UseInterceptors, HttpException, Query, Request } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import e, { Response } from 'express';
import { Answer } from './answer.entity';
import { AnswerService } from './answer.service';
import {
  get,
  post
} from 'request'
import request from 'request'

import {join, resolve} from 'path'
import { createWriteStream } from 'fs';
import {
  wx_appid,
  wx_secret,
  wx_api,
  video_VideoTimeout,
  video_RefererKey,
  system_wx_user
} from '../../setting'
import {
  existsSync,
  mkdirSync
} from 'fs'

import {
  WXAPI
} from '../../common/wx_api'

import {
  apibefore
} from '../../router'
import { ValidRSAInterceptor } from 'src/interceptor/validRSA';
import { ValidTokenInterceptor } from 'src/interceptor/validToken';
import { UserService } from '../user/user.service';
import { PlatformService } from '../platform/platform.service';
import { TraceRelaTable } from '../traceRelaTable/traceRelaTable.entity';
import { WxUserService } from '../wxUser/wxUser.service';
import { WxUser } from '../wxUser/wxUser.entity';
import { MultiImg } from '../multiImg/multiImg.entity';
import utils from 'src/common/utils';
import { ValidUniqueLoginInterceptor } from 'src/interceptor/validUniqueLogin';
@Controller(apibefore('/answer'))
export class AnswerController {
  constructor(private readonly asService: AnswerService,
    private readonly userService: UserService,
    private readonly platformService: PlatformService,
    private readonly wxUserService: WxUserService) {}


  setVideoAnswer_Wx_App(findAnswerResult: any, currentIsGroup: any, multi_img: MultiImg[]){
    let e:any = {
      profit_result:[],
      profit_result_img:[],
      profit_result_img_avatar:[],

    }
    if(multi_img?.length > 0){
      e.multi_img = multi_img.map(e => e.img)
    }
    //自己回答审核通过，或者自己产生利润（返回答案）
    if(findAnswerResult.length > 0){
      let answer:any = []
      let imgs = []
      let img_ids = []
      let avatar_img = []
      let avatar_id = []
      findAnswerResult.map(async c => {
        answer.push({
          platform: c.platform,
          ic_name: c.ic_name,
          account: c.account
        })
        imgs.push(c.img)
        img_ids.push(c.img_id)
        avatar_img.push(c.avatar_img)
        avatar_id.push(c.avatar_id)
        e.profit_works = c.profit_works
      })
      e.profit_result = answer
      e.profit_result_img = imgs
      e.profit_result_img_avatar = avatar_img
    }
    if((e.profit_result || e.profit_result_img || e.profit_result_img_avatar) && currentIsGroup?.length > 0){
      //如果有关联的网红信息
      let answer:any = []
      let imgs = []
      let img_ids = []
      let avatar_img = []
      let avatar_id = []
      currentIsGroup.map(async c => {
        answer.push({
          platform: c.platform,
          ic_name: c.ic_name,
          account: c.account
        })
        
        imgs.push(c.img)
        img_ids.push(c.img_id)
        avatar_img.push(c.avatar_img)
        avatar_id.push(c.avatar_id)
      })
      e.profit_result = answer
      e.profit_result_img = imgs
      e.profit_result_img_avatar = avatar_img
    }
    return e
  }

  /**
   * 查询某个用户某个视频的所有回答列表
   * @param wx_user 
   * @param video_id 
   * @returns 
   */
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  @Get('/getAnswerHistory')
  async getAnswerHistory(@Query() data, @Request() req){
    const wx_user = req.headers.wx_user
    return await this.asService.find_history_by_video_id(wx_user, data.video_id)
  }

  
  /**
   * 获取防盗链视频链接
   * @param currentVideo
   */
  getPlayVideoUrl(currentVideo){
    let oldurl:any = currentVideo.video_url || ''
    let https = 'https://'
    let http = 'http://'
    if(oldurl.indexOf(https) > -1){
      oldurl = oldurl.substring(oldurl.indexOf(https) + https.length)
    }else if(oldurl.indexOf(http) > -1){
      oldurl = oldurl.substring(oldurl.indexOf(http) + http.length)
    }
    oldurl = oldurl.split('/')
    oldurl = oldurl.slice(1,oldurl.length - 1)
    let endTime:string = parseInt((new Date().getTime() / 1000 + video_VideoTimeout).toString()).toString(16)
    let sign = utils.md5(video_RefererKey + '/' + oldurl.join('/') + '/' + endTime)
    if(currentVideo.video_url){
      let newurl = currentVideo.video_url + '?t=' + endTime + '&sign=' + sign
      currentVideo.video_url = newurl
    }
  }
  
  
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  @Get('/get_multi_img')
  async getMultiImg(@Query() data, @Request() req){
    const wx_user = req.headers.wx_user
    let multi_img:any = await this.asService.getMultiImg(data.video_id)
    return multi_img.map(e => e.img)
  }

  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  @Get('/get_answerInfo')
  async getAnswerInfo(@Query() data, @Request() req){
    const wx_user = req.headers.wx_user
    let answer:any = await this.asService.find_answer_by_video_id(wx_user, data.video_id, [data.video_id], data.loadType, data.main)
    let getAnswer = this.setVideoAnswer_Wx_App(answer.user_answer, answer.icGroup, answer.multi_img)
    //根据地址获取防盗链地址 RefererKey
    answer.recommendList.map(currentVideo => {
      this.getPlayVideoUrl(currentVideo)
    })
    this.setVideoAnswer_List(wx_user, answer.recommendList, answer.answerInfo, answer.recommendMultiImg)
    return {relaIcAnswerList: answer.relaIcAnswerList, answer: getAnswer, recommendList: answer.recommendList}
  }

  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  @Get('/get_answer_not_profit')
  async getAnswerNotProfit(@Query() data, @Request() req){
    const wx_user = req.headers.wx_user
    let answer:any = await this.asService.find_answer_by_video_id(wx_user, data.video_id, [], data.loadType)
    let getAnswer = this.setVideoAnswer_Wx_App(answer.user_answer, answer.icGroup, answer.multi_img)
    //根据地址获取防盗链地址 RefererKey
    answer.recommendList.map(currentVideo => {
      this.getPlayVideoUrl(currentVideo)
    })
    this.setVideoAnswer_List(wx_user, answer.recommendList, answer.answerInfo, answer.recommendMultiImg)
    return {answer: getAnswer, recommendList: answer.recommendList}
  }
  

  /**
   * 设置视频答案
   * @param wx_user
   * @param videoList
   */
  async setVideoAnswer_List(wx_user: string, videoList: any, answerList: any, multiImg: any){
    videoList.map((e:any) => {
      let findAnswerList = answerList.filter(c => c.video_id == e.id)
      //视频审核通过的答案编号
      let findOKAnswher = findAnswerList.find(c => c.check == 1)
      e.check_answer = findOKAnswher?.answer_id
      //是否有驳回的答案
      if(!e.check_answer && findAnswerList.find(c => utils.judeAnswerIsReject(c))){
        e.check_answer = 0
      }
      //审核中的答案
      e.is_answer = findAnswerList.find(c => c.check != 1 && c.check !== 0 && c.wx_user == wx_user)?.wx_user
      //自己的所有答案
      e.is_answer_history = findAnswerList.find(c => c.wx_user == wx_user) ? true : false
      if(e.is_answer_history && e.original == 0 && findAnswerList.find(c => c.check == 1 && c.wx_user == e.video_author && c.wx_user == wx_user)){
        e.is_answer_history = false
      }
      //自己回答审核通过，或者自己产生利润（返回答案）
      let findAnswerResult = findAnswerList.filter(c => c.check == 1 && (c.wx_user == wx_user || (c.answer_id && c.use_wx_user == wx_user)))
      if(findAnswerResult.length > 0){
        e.is_profit_result = true
      }
      //自己回答审核通过，或者自己产生利润（返回多图）
      e.multi_img = multiImg.filter(c => c.video_id == e.id && ((c.check == 1 && c.wx_user == wx_user) || (c.answer_id && c.use_wx_user == wx_user)) && c.multi_img).map(c => c.multi_img)
      if(e.multi_img.length === 0){
        delete e.multi_img
      }
      e.multi_img_count = multiImg.filter(c => c.video_id == e.id).length

      let findProfit = findAnswerList.find(c => (c.check == 1 && c.wx_user == wx_user) || (c.answer_id && c.use_wx_user == wx_user))
      e.profit_works = findProfit?.id
      e.profit_status = findProfit?.profit_status
      if(e.video_author == wx_user){
        e.author = true
      }
      e.author_answer = findAnswerList.find(e => e.wx_user == wx_user && e.type != 2) ? true : false
      if(e.video_author === system_wx_user){
        e.system_wx_user = true
      }
      if(wx_user === system_wx_user){
        e.is_system_user = true
      }
      delete e.video_author
      if(e.wx_user_source === wx_user){
        e.author_source = true
      }
      delete e.wx_user_source
    })
  }

  /**
   * 设置视频答案
   * @param wx_user
   */
   async setVideoAnswer(result: any){
    result.data.map(e => {
      let findAnswerResult = result.answerInfo.filter(c => c.answer_id === e.id)
      let answer = []
      let imgs = []
      let avatar_img = []
      findAnswerResult.map(async c => {
        answer.push(`${c.platform}:${c.ic_name}:${c.account||''}`)
        imgs.push(c.img)
        avatar_img.push(c.avatar_img)
      })
      e.answer = answer
      e.img = imgs
      e.avatar_img = avatar_img
    })
    // dataList.map(e => {
    //   e.answer = (e.answer||'').split(',')
    //   e.img = (e.img||'').split(',')
    // })
  }

  @Get('/findAll_Check')
  async findAll_Check(@Query() params){
    let pageSize: number = parseInt(params.pageSize)
    let pageIndex: number = parseInt(params.pageIndex)
    let skip: number = pageSize * pageIndex
    const result = await this.asService.findAll_Check(skip, pageSize, params.keyword, params.searchType)
    this.setVideoAnswer(result)
    return result
  }

  
  @Get('/find_By_Video_auth')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async find_By_Video_auth(@Query() params, @Request() req){
    let findWxUser = await this.userService.findOne(req.headers.token)
    if(!findWxUser){
      return new HttpException('用户不存在',HttpStatus.INTERNAL_SERVER_ERROR)
    }
    return await this.asService.find_By_Video(params.video_id, findWxUser.wx_user)
  }

  @Get('/find_By_Video')
  async find_By_Video(@Query() params, @Request() req){
    let findWxUser = await this.userService.findOne(req.headers.token)
    if(!findWxUser){
      return new HttpException('用户不存在',HttpStatus.INTERNAL_SERVER_ERROR)
    }
    return await this.asService.find_By_Video(params.video_id, findWxUser.wx_user)
  }

  mediaCheckMedia(dataList: any[], wx_user: string){
    let count = dataList.length
    if(count === 0) return true
    let error = false
    return new Promise((resolve,reject) => {
      const wxapi = new WXAPI()
      dataList.map(async (e: any) => {
        if(!error){
          let result:any = await wxapi.mediaCheckAsync(e.img, wx_user)
          if(result?.trace_id){
            e.trace_id = result.trace_id
          }
        }
        count--
        if(count === 0){
          resolve(error ? false : true)
        }
      })
    })
  }


  @Post('/create')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async create(@Body() params: { video_id: number, answer_id?: number, delete_question?: boolean, answer_list?: any },@Request() req) {

    const wx_user = req.headers.wx_user
    //查询用户信息
    let findUserInfo:WxUser = await this.wxUserService.findOne_By_OpenId(wx_appid,wx_user)
    findUserInfo = findUserInfo[0]
    //查询所有平台
    const wxapi = new WXAPI()
    let findPlatformList = await this.platformService.findWXForentUserAnswer_By_Wx_User(wx_user)
    const traceRelaTableList:TraceRelaTable[] = []
    let imgList:any = []
    params.answer_list?.map((e:any) => {
      let item:any = {}
      if(e.ic.img){
        let img_item = {img: e.ic.img}
        imgList.push(img_item)
        item.img = img_item
      }
      if(e.ic.avatar_img){
        let img_item = {img: e.ic.avatar_img}
        imgList.push(img_item)
        item.avatar = img_item
      }
      imgList.push(item)
    })
    let addError = await this.mediaCheckMedia(imgList, findUserInfo.wx_app_openid)
    if(!addError){
      return new HttpException('回答失败，请重试', HttpStatus.INTERNAL_SERVER_ERROR)
    }
    imgList.map(e => {
      if(e.img){
        let findItem = params.answer_list.find(c => c.ic.img == e.img.img)
        if(findItem){
          e.trace_id = e.img.trace_id
        }
      }
    })
    let text = findPlatformList.map(e => e.platform + ':' + e.ic_name).join(',')
    let result:any = await wxapi.msgSecCheck(text, findUserInfo.wx_app_openid)
    if(result.result?.suggest == 'risky'){
      return new HttpException('存在非法内容', HttpStatus.INTERNAL_SERVER_ERROR)
    }
    imgList.map(e => {
      //创建任务、表关联
      let addTrace = new TraceRelaTable()
      addTrace.trace_id = e.trace_id
      addTrace.table = 'answer_info'
      addTrace.create_time = new Date()
      traceRelaTableList.push(addTrace)
    })
    if(params.answer_id){
      return await this.asService.answerUpdate(params.video_id, wx_user, findPlatformList, traceRelaTableList, params.answer_id, params.answer_list || [])
    }else{
      return await this.asService.answerCreate(params.video_id, wx_user, findPlatformList, traceRelaTableList, params.delete_question, params.answer_list || [])
    }
  }



  @Post('/create2')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async create2(@Body() params: { video_id: number, answer: string, wx_user: string}) {
    let result:any = await new WXAPI().msgSecCheck(params.answer, params.wx_user)
    console.log('msgSecCheckmsgSecCheckmsgSecCheckmsgSecCheckmsgSecCheck---------------------------------------')
    console.log(result)
    console.log('msgSecCheckmsgSecCheckmsgSecCheckmsgSecCheckmsgSecCheck---------------------------------------')
    if(result.result?.label == 100){
      const qa = new Answer()
      qa.video_id = params.video_id
      qa.answer = params.answer
      qa.wx_user = params.wx_user
      qa.create_time = new Date()
      return await this.asService.create(qa)
    }else{
      return new HttpException('存在非法内容', HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }



  @Post('/check_auth')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async check_auth(@Body() params: { id: number; check: number }) {
    let findAnswer = await this.asService.findById(params.id)
    if(!findAnswer) return new HttpException('答案不存在', HttpStatus.INTERNAL_SERVER_ERROR)
    let as = new Answer()
    as.id = params.id
    as.check = params.check
    as.check_time = new Date()
    as.video_id = findAnswer.video_id
    let err = ''
    if(as.check == 1){
      err = await this.asService.check(as)
    }else{
      err = await this.asService.update(as)
    }
    if(err){
      return new HttpException(err, HttpStatus.INTERNAL_SERVER_ERROR)
    }else{
      return true
    }
  }


  @Post('/check')
  async check(@Body() params: { id: number; check: number }) {
    let findAnswer = await this.asService.findById(params.id)
    if(!findAnswer) return new HttpException('答案不存在', HttpStatus.INTERNAL_SERVER_ERROR)
    let as = new Answer()
    as.id = params.id
    as.check = params.check
    as.check_time = new Date()
    as.video_id = findAnswer.video_id
    let err = ''
    if(as.check == 1){
      err = await this.asService.check(as)
    }else{
      err = await this.asService.update(as)
    }
    if(err){
      return new HttpException(err, HttpStatus.INTERNAL_SERVER_ERROR)
    }else{
      return true
    }
  }

  
  @Get('/findAll_By_Question_auth')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async findAll_By_Question_auth(@Query() params){
    let pageSize: number = parseInt(params.pageSize)
    let pageIndex: number = parseInt(params.pageIndex)
    let skip: number = pageSize * pageIndex
    return await this.asService.findAll_By_Question(skip, pageSize, params.video_id)
  }


  @Get('/findAll_By_Question')
  async findAll_By_Question(@Query() params){
    let pageSize: number = parseInt(params.pageSize)
    let pageIndex: number = parseInt(params.pageIndex)
    let skip: number = pageSize * pageIndex
    return await this.asService.findAll_By_Question(skip, pageSize, params.video_id)
  }

  @Get('/findMyAnswer')
  async findMyAnswer(@Query() params: { wx_user: string}){
    return await this.asService.findList_By_wx_user_key(params.wx_user)
  }

  @Get('/findAll')
  async findAll() {

  }

  deleteVideo(FileId: string, then: Function, catchF: Function){

  }

  @Post('/delete_by_video_id')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async deleteByVideoId(@Request() req, @Body() data){
    let wx_user = req.headers.wx_user
    let video_id = data.video_id
    let err = await this.asService.deleteByVideoId(video_id, wx_user)
    if(err){
      return new HttpException(err || '删除失败', HttpStatus.INTERNAL_SERVER_ERROR)
    }else{
      return true
    }
  }

  @Post('/delete_ischeck_by_video_id')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async deleteIsCheckByVideoId(@Request() req, @Body() data){
    let wx_user = req.headers.wx_user
    let video_id = data.video_id
    let err = await this.asService.deleteIsCheckByVideoId(video_id, wx_user)
    if(err){
      return false
    }else{
      return true
    }
  }

  /**
   * 第一堆答案被拒绝，删除答案
   * @param req 
   * @param data 
   * @returns 
   */
  @Post('/delete_answer_is_reject')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async deleteAnswerIsReject(@Request() req, @Body() data){
    let wx_user = req.headers.wx_user
    let video_id = data.video_id
    let err = await this.asService.deleteAnswerIsReject(video_id, wx_user)
    if(err){
      return false
    }else{
      return true
    }
  }
  
  @Post('/checkAnswer')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  async CheckAnswer(@Body() params: { answer_id: number; ic_group: number }, @Request() req) {
    let err = await this.asService.CheckAnswer(params.answer_id, req.headers.token)
    if(err){
      return new HttpException(err, HttpStatus.INTERNAL_SERVER_ERROR)
    }
    return true
  }

  @Post('/rejectAnswer')
  @UseInterceptors(ValidUniqueLoginInterceptor)
  rejectAnswer(@Body() params: { answer_id: number, reject_reason: number }, @Request() req) {
    return this.asService.rejectAnswer(params.answer_id, req.headers.token, params.reject_reason)
  }


}
